<template>
  <Top-Page class="tx-box">
    <cu-custom bgColor="bg-gradual-white-3" :isBack="true">
      <template #content>通话</template>
    </cu-custom>

    <TUICallKit class="t-ui-call" :afterCalling="navBack" :beforeCalling="beforeCalling" />
  </Top-Page>
</template>

<script lang="ts" setup>
import api from "@/api/index.js";

import { onLoad } from "@dcloudio/uni-app";

import { TIM, TUITIM, TUICallKit, TUICallKitServer } from "@/utils/trtc.js";
// #ifdef H5
import { useMsgStore } from "@/store/message";
import pinia from "@/store/index";
import { onBeforeUnmount, ref } from "vue";

console.log(TUICallKit, "TUICallKit??????????????");

const msgStore = useMsgStore(pinia);

const memberLists = msgStore.memberList;
const userInfo = uni.getStorageSync("userInfo");
const user_id = String(userInfo.user_id);
let roomID = Number(userInfo.user_id);
const query: any = {};

onLoad((params: any) => {
  Object.assign(query, params);
  console.log("进入电话页面");
  if (params.status === "call") {
    roomID = Number(userInfo.user_id);
    if (!memberLists.length) {
      uni.showToast({
        title: "通话异常，请重新拨打",
        icon: "none",
      });

      uni.reLaunch({
        url: "/pages/index/index",
      });

      return;
    }
  } else {
    roomID = Number(query.toContactId);
  }

  //设置用户昵称、头像。
  setSelfInfo();
});

async function setSelfInfo() {
  const options = {
    nickName: userInfo.realname,
    avatar: userInfo.avatar,
  };

  await TUICallKitServer.setSelfInfo(options);

  query.status === "call"
    ? //发起通话
      groupCall()
    : //加入群组通话
      joinInGroupCall();
}

async function createGroupID() {
  let groupID = userInfo.groupID ?? "";
  if (groupID) {
    return groupID;
  } else {
    const memberList: any[] = memberLists.map((item: any) => ({ userID: String(item.userID) }));

    const res = await TUITIM.createGroup({
      type: TIM.TYPES.GRP_PUBLIC,
      name: "群视频",
      memberList,
      // joinOption: TIM.TYPES.JOIN_OPTIONS_FREE_ACCESS,
    });

    groupID = res.data.group.groupID;

    //记住创建的groupID
    userInfo["groupID"] = groupID;
    uni.setStorageSync("userInfo", userInfo);

    return groupID;
  }
}

async function groupCall() {
  const userIDList = memberLists.map((item: { userID: any }) => String(item.userID));
  const groupID = await createGroupID();

  const options = {
    groupID: groupID,
    userIDList: userIDList,
    type: Number(query.type),
  };

  msgCallback("calling", groupID);

  console.log("发起通话", options);

  TUICallKitServer.groupCall(options);
}

//加入群组通话
function joinInGroupCall() {
  // const options = {
  //   type: Number(query.type),
  //   groupID: query.groupID,
  //   roomID: query.roomID,
  // };
  // console.log("加入群组通话", options);
  // TUICallKitServer.joinInGroupCall(options, (res) => {
  //   if (res.code === 0) {
  //     console.log("join success");
  //   } else {
  //     console.log(`join failed, error message = ${res.msg}`);
  //     navBack();
  //   }
  // });
}

async function msgCallback(event: string, groupID: string) {
  const call_user_id = memberLists.map((item: { userID: number }) => item.userID);

  await api.msgApi
    .sendToGroupMsg({
      event: event,
      call_user_id: call_user_id,
      type: 2,
      groupID: groupID,
      roomID: userInfo.user_id,
      msg_id: query.msg_id,
      status: event === "calling" ? 1 : 0,
      code: "",
      callTime: "",
      sdp: "",
      iceCandidate: "",
      toContactId: String(query.id),
    })
    .then((res) => {
      if (res.data.extends?.code == 907) {
        uni.showToast({
          title: "对方不在线",
          icon: "none",
        });
        navBack();
      }
    });
}

const beforeCalling = (e) => {
  console.log(e, "拨打电话前与收到通话邀请前会执行此函数");
};

const statusChanged = (e) => {
  console.log("----------通话状态发生变化-----------");
  console.log(e);
  if (e.newStatus === "idle") {
    console.log("挂断");
  } else if (e.newStatus === "calling-group") {
    console.log("正在群组呼叫");
  } else if (e.newStatus === "calling-group-video") {
    console.log("正在群组视频通话");
  }
};

function navBack() {
  uni.navigateBack({
    delta: 1,
  });
}

// #endif
</script>

<style lang="scss" scoped>
.tx-box {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  overflow: hidden;

  .t-ui-call {
    flex: 1;
  }
}
</style>
